const Koa = require("koa");
const Router = require("koa-router");
const views = require("koa-views");
const static = require("koa-static");
let app = new Koa();
let router = new Router();

const server = require('http').createServer(app.callback());
const io = require('socket.io')(server);
let arr = [];
// 监听websocket连接
io.on("connection",socket=>{
    console.log("有连接过来了");
    // on ---> addEventlistener   emit ---》事件（click、mouseover...）
    socket.on("addmessage",function(res){
        // console.log(res);
        // 接收客户端的数据，在通过服务端推送给客户端
        // 只会发送事件给当前连接的客户端
        arr.push(res);
        socket.emit("sendmessage",arr);
        // 广播给其他所有的socket连接
        socket.broadcast.emit("sendmessage",arr);
    })
})
app.use(views(__dirname+"/views"));
app.use(static(__dirname+"/static"));
router.get("/index",async ctx=>{
   await ctx.render("index.html");
});

router.get("/getdata",async ctx=>{
    ctx.body = [{name:"张三",age:20},{name:"李四",age:21},{name:"王五",age:23}]
});

app.use(router.routes());
server.listen(8989);

// 作业：1.复习 2.拖拽方块 --->2个页面的方块拖拽同步